#include "InputManager.h"
#include "Globals.h"


InputManager::InputManager()
{
}


InputManager::~InputManager()
{
}

bool InputManager::LoadBindings()
{
	bool result = true;
	std::ifstream infile(CONFIG_FILE_PATH);
	std::string line;
	while (std::getline(infile, line))
	{
		std::istringstream iss(line);
		std::string key, value;
		if (!(iss >> key >> value)) 
		{ 
			result = false;
			break; 
		} // error
		key.pop_back();
		if (value == "space_bar") m_bindings[key] = ' ';
		else if (value == "right_click") m_bindings[key] = 257;
		else if (value == "left_click") m_bindings[key] = 256;
		else if (value == "right_arrow") m_bindings[key] = GLUT_KEY_RIGHT;
		else if (value == "left_arrow") m_bindings[key] = GLUT_KEY_LEFT;
		else if (value == "up_arrow") m_bindings[key] = GLUT_KEY_UP;
		else if (value == "down_arrow") m_bindings[key] = GLUT_KEY_DOWN;
		else
		{
			m_bindings[key] = value[0];
		}
		std::cout << "action " << key << " has value of: " << m_bindings[key] << std::endl;
	}
	return result;
}

int InputManager::GetBinding(std::string key)
{
	return m_bindings[key];
}

void InputManager::Shuffle()
{
	std::vector< std::pair< std::string, int> > bindingsShuffler(m_bindings.size());
	int j = 0;
	for (auto i : m_bindings)
	{
		bindingsShuffler[j++] = (i);
	}
	j = 0;
	_shuffleVector(&bindingsShuffler);
	for (int i = 0; i < bindingsShuffler.size(); ++i)
	{
		m_bindings[bindingsShuffler[i].first] = bindingsShuffler[i].second;
	}
}

void InputManager::_shuffleVector(std::vector<std::pair<std::string, int> > * bindings)
{
	for (int i = 0; i < bindings->size(); ++i)
	{
		std::string aux = (*bindings)[i].first;
		int random = std::rand() % (*bindings).size();
		(*bindings)[i].first = (*bindings)[random].first;
		(*bindings)[random].first = aux;
	}
}
